//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.eshop.modules.mp.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.live.WxMaLiveResult;
import cn.binarywang.wx.miniapp.bean.live.WxMaLiveResult.LiveReplay;
import cn.binarywang.wx.miniapp.bean.live.WxMaLiveResult.RoomInfo;
import cn.binarywang.wx.miniapp.json.WxMaGsonBuilder;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eshop.common.service.impl.BaseServiceImpl;
import com.eshop.common.utils.QueryHelpPlus;
import com.eshop.dozer.service.IGenerator;
import com.eshop.exception.BadRequestException;
import com.eshop.modules.mp.config.WxMaConfiguration;
import com.eshop.modules.mp.domain.WechatLive;
import com.eshop.modules.mp.domain.WechatLiveGoods;
import com.eshop.modules.mp.service.WechatLiveGoodsService;
import com.eshop.modules.mp.service.WechatLiveService;
import com.eshop.modules.mp.service.dto.UpdateGoodsDto;
import com.eshop.modules.mp.service.dto.WechatLiveDto;
import com.eshop.modules.mp.service.dto.WechatLiveGoodsDto;
import com.eshop.modules.mp.service.dto.WechatLiveQueryCriteria;
import com.eshop.modules.mp.service.mapper.WechatLiveMapper;
import com.eshop.modules.mp.vo.WechatLiveVo;
import com.eshop.utils.FileUtil;
import com.eshop.utils.OrderUtil;
import com.eshop.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.enums.WxType;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(
        propagation = Propagation.REQUIRED,
        readOnly = false,
        rollbackFor = {Exception.class}
)
public class WechatLiveServiceImpl extends BaseServiceImpl<WechatLiveMapper, WechatLive> implements WechatLiveService {
    private static final Logger log = LoggerFactory.getLogger(WechatLiveServiceImpl.class);
    private final IGenerator generator;
    @Value("${file.path}")
    private String uploadDirStr;
    private final WechatLiveGoodsService wechatLiveGoodsService;
    private final WechatLiveMapper wechatLiveMapper;

    public WechatLiveServiceImpl(IGenerator generator, WechatLiveGoodsService wechatLiveGoodsService, WechatLiveMapper wechatLiveMapper) {
        this.generator = generator;
        this.wechatLiveGoodsService = wechatLiveGoodsService;
        this.wechatLiveMapper = wechatLiveMapper;
    }

    public boolean synchroWxOlLive() {
        try {
            WxMaService wxMaService = WxMaConfiguration.getWxMaService();
            List<RoomInfo> liveInfos = wxMaService.getLiveService().getLiveInfos();
            List<WechatLive> convert = this.generator.convert(liveInfos, WechatLive.class);
            this.saveOrUpdateBatch(convert);
        } catch (WxErrorException var4) {
            var4.printStackTrace();
        }

        return true;
    }

    public WechatLiveVo queryAll(WechatLiveQueryCriteria criteria, Pageable pageable) {
        String order = null;
        if (pageable.getSort() != null) {
            order = pageable.getSort().toString();
            order = order.replace(":", "");
            if ("UNSORTED".equals(order)) {
                order = "start_time desc";
            }
        }

        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize(), order);
        PageInfo<WechatLive> page = new PageInfo(this.queryAll(criteria));
        WechatLiveVo wechatLiveVo = new WechatLiveVo();
        List<WechatLiveDto> liveDtos = this.generator.convert(page.getList(), WechatLiveDto.class);
        liveDtos.forEach((i) -> {
            if (StringUtils.isNotBlank(i.getProductId())) {
                List<WechatLiveGoodsDto> wechatLiveGoodsDtos = this.generator.convert(this.wechatLiveGoodsService.list((Wrappers.<WechatLiveGoods>lambdaQuery()).in(WechatLiveGoods::getGoodsId, i.getProductId().split(","))), WechatLiveGoodsDto.class);
                i.setProduct(wechatLiveGoodsDtos);
            }

            i.setId(i.getRoomId());
        });
        wechatLiveVo.setContent(liveDtos);
        wechatLiveVo.setTotalElements(page.getTotal());
        wechatLiveVo.setPageNumber(page.getPageNum());
        wechatLiveVo.setLastPage(page.getPages());
        return wechatLiveVo;
    }

    public boolean addGoods(UpdateGoodsDto resources) {
        WechatLive wechatLive = new WechatLive();
        WxMaService wxMaService = WxMaConfiguration.getWxMaService();
        if (StringUtils.isNotBlank(resources.getProductId())) {
            wechatLive.setRoomId((long)resources.getRoomId());
            wechatLive.setProductId(resources.getProductId());
            String[] productIds = resources.getProductId().split(",");
            List<Integer> pids = new ArrayList();
            String[] var6 = productIds;
            int var7 = productIds.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                String productId = var6[var8];
                pids.add(Integer.valueOf(productId));
            }

            try {
                wxMaService.getLiveService().addGoodsToRoom(resources.getRoomId(), pids);
                this.saveOrUpdate(wechatLive);
            } catch (WxErrorException var10) {
                var10.printStackTrace();
            }
        }

        return true;
    }

    public boolean saveLive(WechatLive resources) {
        WxMaService wxMaService = WxMaConfiguration.getWxMaService();

        try {
            resources.setStartTime((long)OrderUtil.dateToTimestamp(resources.getStartDate()));
            resources.setEndTime((long)OrderUtil.dateToTimestamp(resources.getEndDate()));
            resources.setAnchorImg(this.uploadPhotoToWx(wxMaService, resources.getAnchorImge()).getMediaId());
            resources.setCoverImg(this.uploadPhotoToWx(wxMaService, resources.getCoverImge()).getMediaId());
            resources.setShareImg(this.uploadPhotoToWx(wxMaService, resources.getShareImge()).getMediaId());
            com.eshop.modules.mp.service.dto.WxMaLiveInfo.RoomInfo roomInfo = (com.eshop.modules.mp.service.dto.WxMaLiveInfo.RoomInfo)this.generator.convert(resources, com.eshop.modules.mp.service.dto.WxMaLiveInfo.RoomInfo.class);
            Integer status = this.createRoom(roomInfo);
            resources.setRoomId((long)status);
            if (StringUtils.isNotBlank(resources.getProductId())) {
                String[] productIds = resources.getProductId().split(",");
                List<Integer> pids = new ArrayList();
                String[] var7 = productIds;
                int var8 = productIds.length;

                for(int var9 = 0; var9 < var8; ++var9) {
                    String productId = var7[var9];
                    pids.add(Integer.valueOf(productId));
                }

                wxMaService.getLiveService().addGoodsToRoom(status, pids);
            }

            this.save(resources);
            return false;
        } catch (WxErrorException var11) {
            var11.printStackTrace();
            throw new BadRequestException(var11.toString());
        }
    }

    public List<WechatLive> queryAll(WechatLiveQueryCriteria criteria) {
        return ((WechatLiveMapper)this.baseMapper).selectList(QueryHelpPlus.getPredicate(WechatLive.class, criteria));
    }

    public List<LiveReplay> getLiveReplay(Integer roomId) {
        WxMaService wxMaService = WxMaConfiguration.getWxMaService();
        WxMaLiveResult get_replay = new WxMaLiveResult();

        try {
            get_replay = wxMaService.getLiveService().getLiveReplay("get_replay", roomId, 0, 100);
        } catch (WxErrorException var5) {
            var5.printStackTrace();
        }

        return get_replay.getLiveReplay();
    }

    public void download(List<WechatLiveDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList();
        Iterator var4 = all.iterator();

        while(var4.hasNext()) {
            WechatLiveDto yxWechatLive = (WechatLiveDto)var4.next();
            Map<String, Object> map = new LinkedHashMap();
            map.put("直播间标题", yxWechatLive.getName());
            map.put("背景图", yxWechatLive.getCoverImge());
            map.put("分享图片", yxWechatLive.getShareImge());
            map.put("直播间状态", yxWechatLive.getLiveStatus());
            map.put("开始时间", yxWechatLive.getStartTime());
            map.put("预计结束时间", yxWechatLive.getEndTime());
            map.put("主播昵称", yxWechatLive.getAnchorName());
            map.put("主播微信号", yxWechatLive.getAnchorWechat());
            map.put("主播头像", yxWechatLive.getAnchorImge());
            map.put("直播间类型 1：推流 0：手机直播", yxWechatLive.getType());
            map.put("横屏、竖屏 【1：横屏，0：竖屏】", yxWechatLive.getScreenType());
            map.put("是否关闭货架 【0：开启，1：关闭】", yxWechatLive.getCloseLike());
            map.put("是否关闭评论 【0：开启，1：关闭】", yxWechatLive.getCloseComment());
            list.add(map);
        }

        FileUtil.downloadExcel(list, response);
    }

    public Integer createRoom(com.eshop.modules.mp.service.dto.WxMaLiveInfo.RoomInfo roomInfo) throws WxErrorException {
        WxMaService wxMaService = WxMaConfiguration.getWxMaService();
        String responseContent = wxMaService.post("https://api.weixin.qq.com/wxaapi/broadcast/room/create", WxMaGsonBuilder.create().toJson(roomInfo));
        JsonObject jsonObject = GsonParser.parse(responseContent);
        if (jsonObject.get("errcode").getAsInt() != 0) {
            throw new WxErrorException(WxError.fromJson(responseContent, WxType.MiniApp));
        } else {
            return jsonObject.get("roomId").getAsInt();
        }
    }

    private WxMediaUploadResult uploadPhotoToWx(WxMaService wxMaService, String picPath) throws WxErrorException {
        String filename = (int)System.currentTimeMillis() + ".png";
        String downloadPath = this.uploadDirStr + filename;
        HttpUtil.downloadFile(picPath, cn.hutool.core.io.FileUtil.file(downloadPath));
        File picFile = new File(downloadPath);
        log.info("picFile name : {}", picFile.getName());
        WxMediaUploadResult wxMediaUploadResult = wxMaService.getMediaService().uploadMedia("image", picFile);
        log.info("wxMpMaterialUploadResult : {}", JSONUtil.toJsonStr(wxMediaUploadResult));
        return wxMediaUploadResult;
    }

    public List<WechatLiveDto> getList(int page, int limit, int order) {
        LambdaQueryWrapper<WechatLive> wrapper = new LambdaQueryWrapper();
        wrapper.orderByDesc(WechatLive::getStartTime);
        Page<WechatLive> pageModel = new Page((long)page, (long)limit);
        IPage<WechatLive> pageList = this.wechatLiveMapper.selectPage(pageModel, wrapper);
        return this.generator.convert(pageList.getRecords(), WechatLiveDto.class);
    }
}
